package com.process.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.process.controller.util.Code;
import com.process.controller.util.R;
import com.process.dao.outer.*;
import com.process.dao.pojoDao.CompanyDao;
import com.process.dao.pojoDao.PracticeCourseDao;
import com.process.dao.publish.CourseTaskPublishVoDao;
import com.process.dao.voDao.*;
import com.process.domain.outer.CompanyEvaluationVo;
import com.process.domain.outer.CourseHistory;
import com.process.domain.outer.OutTeacherVo;
import com.process.domain.publi.Class;
import com.process.domain.publi.*;
import com.process.domain.publish.CampusInnerPublishVo;
import com.process.domain.publish.CourseTaskPublishVo;
import com.process.domain.publish.TaskBase;
import com.process.service.ExcelServ.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description:
 * @ClassName: ExcelController
 * @Author: 殷凡卓
 * @Date: 2023/4/21 14:10
 */
@RestController
@Slf4j
@CrossOrigin(origins = "*")
@RequestMapping("/excel")
public class AdminController {

    @Autowired
    private PracticalTaskService practicalTaskService;
    @Autowired
    private TrainPlanService trainPlanService;
    @Autowired
    private PracticeCourseService practiceCourseService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;

    @Autowired
    private StudentVoDao studentVoDao;
    @Autowired
    private TeacherVoDao teacherVoDao;
    @Autowired
    private OutTeacherVoDao outTeacherVoDao;
    @Autowired
    private PracticalTaskVoDao practicalTaskVoDao;
    @Autowired
    private FindTaskVoDao findTaskVoDao;
    @Autowired
    private FindCourseTaskVoDao findCourseTaskVoDao;
    @Autowired
    private PracticeCourseVoDao practiceCourseVoDao;
    @Autowired
    private TrainPlanVoDao trainPlanVoDao;
    @Autowired
    private AdminVoDao adminVoDao;
    @Autowired
    private CompanyEvaluationVoDao companyEvaluationVoDao;
    @Autowired
    private CompanyEvaluationDao companyEvaluationDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private AdminDataAnalysisDao adminDataAnalysisDao;

    @Autowired
    private PracticeCourseDao practiceCourseDao;
    @Autowired
    private CourseTaskPublishVoDao courseTaskPublishVoDao;
    @Autowired
    private CampusInnerPublishVoDao campusInnerPublishVoDao;
    @Autowired
    private ClassService classService;

    @SneakyThrows
    @PostMapping("/import_PracticalTask")
    public R import_PracticalTask(@RequestParam("file") MultipartFile file,
                                  HttpServletRequest request) throws IOException {

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<PracticalTask> list = reader.readAll(PracticalTask.class);
        //批量插入
        list.forEach(e ->   {
            System.out.println(e);
        });
        practicalTaskService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    @SneakyThrows
    @PostMapping("/import_Class")
    public R import_Class(@RequestParam("file") MultipartFile file,
                          HttpServletRequest request) throws IOException {

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<Class> list = reader.readAll(Class.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });
        classService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    @SneakyThrows
    @PostMapping("/import_TrainPlan")
    public R import_TrainPlan(@RequestParam("file") MultipartFile file,
                              HttpServletRequest request) throws IOException {


        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<TrainPlan> list = reader.readAll(TrainPlan.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });

        trainPlanService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    @SneakyThrows
    @PostMapping("/import_PracticeCourse")
    public R import_PracticeCourse(@RequestParam("file") MultipartFile file,
                                   HttpServletRequest request) throws IOException {

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<PracticeCourse> list = reader.readAll(PracticeCourse.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });
        practiceCourseService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    //@RequestParam("token") String token
    @SneakyThrows
    @PostMapping("/import_Teacher")
    public R import_Teacher(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request) throws IOException {
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
//        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");

//        jwtUtils.verify(token, request);
//        String username = (String) request.getAttribute("username");
//        log.info("/import_Teacher的电话{}", username);
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<Teacher> list = reader.readAll(Teacher.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });
        teacherService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }
    //记住了，往下是李春la的-----------------------------------------

    //    @RequestParam("token") String token,
    @SneakyThrows
    @PostMapping("/import_Student")
    public R import_Student(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request) throws IOException {

//        jwtUtils.verify(token, request);
//        String username = (String) request.getAttribute("username");
//        log.info("/import_Student的电话{}", username);

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<Student> list = reader.readAll(Student.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });
        studentService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    @Autowired
    private TaskBaseService taskBaseService;


    @SneakyThrows
    @PostMapping("/import_TaskBase")
    public R import_TaskBase(
//                             @RequestParam("token") String token,
                             @RequestParam("file") MultipartFile file,
                             HttpServletRequest request) throws IOException {

//        jwtUtils.verify(token, request);
//        String username = (String) request.getAttribute("username");
//        log.info("/import_TaskBase的电话{}", username);

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //注意 这里的参数 是List集合中的实体类型
        List<TaskBase> list = reader.readAll(TaskBase.class);
        //批量插入
        list.forEach(e -> {
            System.out.println(e);
        });
        taskBaseService.saveBatch(list);
        return new R(Code.SAVE_OK,null,"上传成功");
    }

    /**
     * author：李春
     *
     * @param servletRequest
     * @return
     */
    @GetMapping("/allStudentDetail")
    public R getallStudentDetail(ServletRequest servletRequest) {

        log.info("获取所有学生的详细信息");
        List<StudentVo> studentVos = studentVoDao.selectAllStudentDetail();

        return new R(Code.GET_OK, studentVos, "查询我的详细信息");
    }

    /**
     * 查看班级信息
     * author 殷凡卓
     * @param servletRequest
     * @return
     */
    @GetMapping("/allClass")
    public R getallclass(ServletRequest servletRequest) {

        log.info("获取所有学生的详细信息");
        List<Class> list = classService.list();

        return new R(Code.GET_OK, list, "查询全部班级信息");
    }


    @GetMapping("/allInnerTeacherDetail")
    public R getallInnerTeacherDetail(ServletRequest servletRequest) {

        log.info("获取所有校内老师的详细信息");
        List<Teacher> teachers = teacherVoDao.selectAllInnerTeacherDetail();
        return new R(Code.GET_OK, teachers, "查询所有校内老师的详细信息");
    }

    @GetMapping("/allOuterTeacherDetail")
    public R getallOuterTeacherDetail(ServletRequest servletRequest) {


        log.info("获取所有校外老师的详细信息");
        List<OutTeacherVo> outTeacherVos = outTeacherVoDao.selectAllOuterTeacherDetail();
        return new R(Code.GET_OK, outTeacherVos, "查询所有校外老师的详细信息");
    }

    @GetMapping("/allPracticeCourseVo")
    public R getallPracticeCourseVo(ServletRequest servletRequest) {

        log.info("获取所有课程安排的详细信息");
        List<PracticeCourse> practiceCourses = practiceCourseVoDao.selectAllPracticeCourseVo();
        return new R(Code.GET_OK, practiceCourses, "查询所有课程安排的详细信息");
    }

    @GetMapping("/allTrainPlanVo")
    public R getallTrainPlanVo(ServletRequest servletRequest) {

        log.info("获取所有培养方案的详细信息");
        List<TrainPlan> trainPlans = trainPlanVoDao.selectAllTrainPlanVo();
        return new R(Code.GET_OK, trainPlans, "获取所有培养方案的详细信息");
    }

    @GetMapping("/allPraDetailVo")
    public R getallPraDetailVo(ServletRequest servletRequest) {

        log.info("获取所有课题任务的详细信息");
        List<PracticalTaskVo> practicalTaskVos = practicalTaskVoDao.selectPraticalVo();
        return new R(Code.GET_OK, practicalTaskVos, "查询所有课题任务安排的详细信息");
    }

    @GetMapping("/allouterTaskVo")
    public R getallouterTaskVo(ServletRequest servletRequest) {

        log.info("获取所有校外历史发布的详细信息");
        List<CourseHistory> courseHistories1 = findTaskVoDao.selectAllouterTaskVo();
        return new R(Code.GET_OK, courseHistories1, "查询所有校外历史发布的详细信息");
    }


    /**
     * inner发布历史
     * author 殷凡卓
     *
     * @param servletRequest
     * @return
     */
    @GetMapping("/allinnerTaskVo")
    public R getallinnerTaskVo(ServletRequest servletRequest) {
        log.info("获取所有校内历史发布的详细信息");
        List<CampusInnerPublishVo> campusInnerPublishVos = campusInnerPublishVoDao.selectAllTeacher();

        return new R(Code.GET_OK, campusInnerPublishVos, "查询所有校内历史发布的详细信息");
    }

    /**
     * course发布历史
     * author 殷凡卓
     *
     * @param servletRequest
     * @return
     */
    @GetMapping("/allcourseTaskVo")
    public R getallcourseTaskVo(ServletRequest servletRequest) {
        log.info("获取所有课程历史发布的详细信息");
        List<CourseTaskPublishVo> courseTaskPublishVos = courseTaskPublishVoDao.selectVoAllteacher();

        return new R(Code.GET_OK, courseTaskPublishVos, "查询所有课程历史发布的详细信息");
    }


    @GetMapping("/allstuEvaluationVo")
    public R getallstuEvaluationVo(ServletRequest servletRequest) {

        log.info("获取所有学生发的评论");
        List<CompanyEvaluationVo> companyEvaluationVos = companyEvaluationVoDao.selectAllStudentEvaluation();
        return new R(Code.GET_OK, companyEvaluationVos, "获取所有学生发的评论");
    }

    @GetMapping("deletestuEvaluation/{evalustioniId}")
    public R deleteouterPublishByPublishId(@PathVariable long evalustioniId, ServletRequest servletRequest) {

        int delete = companyEvaluationDao.delete(new LambdaQueryWrapper<CompanyEvaluation>().eq(CompanyEvaluation::getEvaluationId, evalustioniId));
//        int delete1 = campusOffPublishDao.delete(new LambdaQueryWrapper<CampusOffPublish>().eq(CampusOffPublish::getPublishId, publishId));
        if (delete > 0)
            return new R(Code.DELETE_OK, delete, "删除outerpublish成功");
        else
            return new R(Code.DELETE_ERR, delete, "删除outerpublish失败");

    }

    @PostMapping("/addCompany")
    public R postaddCompany(ServletRequest servletRequest, @RequestBody Company company) {

        try {

            companyDao.insert(company);
            return new R(Code.GET_OK, null, "提交企业信息成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("错错错");
            return new R(Code.GET_ERR, null, "添加企业失败");
        }
    }

    @GetMapping("deleteCompany/{companyId}")
    public R deleteCompany(@PathVariable long companyId, ServletRequest servletRequest) {
        int delete1 = companyDao.delete(new LambdaQueryWrapper<Company>().eq(Company::getCompanyId, companyId));

        if (delete1 > 0)
            return new R(Code.DELETE_OK, delete1, "删除成功");
        else
            return new R(Code.DELETE_ERR, delete1, "删除失败");

    }

    //数据分析
    @GetMapping("/AdmindataAnalysisOne")
    public R AdmindataAnalysisOne(ServletRequest servletRequest) {

        List<Map<String, Object>> data1 = adminDataAnalysisDao.dataFindOne();

        return new R(Code.GET_OK, data1, "获取最高分最低分平均分成功！");

    }

    @GetMapping("/AdmindataAnalysisTwo")
    public R AdmindataAnalysisTwo(ServletRequest servletRequest) {

        List<Map<String, Object>> data2 = adminDataAnalysisDao.dataFindTwo();

        return new R(Code.GET_OK, data2, "获取区间分和成功率成功！");

    }
//管理员的token失效
//    @GetMapping("/adminDetail")
//    public R getadminDetailByAdminPhone(ServletRequest servletRequest) {
//        String phone = (String) servletRequest.getAttribute("username");
//        log.info(phone);
//        log.info("545646456");
//        List<Admin> admins = adminVoDao.selectAdminVoByAdminPhone(phone);
//        return new R(Code.GET_OK, admins, "获取我的详细信息");
//    }

//
//    @SneakyThrows
//    @PostMapping("/import_PracticeCourse/test")
//    public R import_test(@RequestParam(value = "token",required = true) String token,@RequestParam("file") MultipartFile file) throws IOException {
//
//        log.info("文件token获取",token);
//
//        InputStream inputStream = file.getInputStream();
//        ExcelReader reader = ExcelUtil.getReader(inputStream);
//        //注意 这里的参数 是List集合中的实体类型
//        List<PracticeCourse> list = reader.readAll(PracticeCourse.class);
//        //批量插入
//        list.forEach(e -> {
//            System.out.println(e);
//        });
//        practiceCourseService.saveBatch(list);
//        return new R(Code.SAVE_OK);
//    }


    /**
     * 上传大纲
     *
     * @param courseId
     * @param file
     * @return
     */
    @PostMapping("/upload/practiceCourse/{courseId}")
    public R uploadFile(@PathVariable long courseId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {

            return new R(Code.SAVE_ERR, null, "文件上传失败，请选择文件");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        //文件基础路径
        String fileBasePath = "D:/IdeaProject/ProcessManagement/practiceCourse/";
        File mkdir = new File(fileBasePath);
        // 创建文件夹（如果不存在）
        if (!mkdir.exists()) {
            boolean created = mkdir.mkdir();
            if (created) {
                System.out.println("文件夹创建成功！");
            } else {
                System.out.println("文件夹创建失败！");
            }
        }

        //上穿文件夹
        try {

            String randomStr = UUID.randomUUID().toString();
            String fileExtension = FilenameUtils.getExtension(fileName);
            String newFileName = FilenameUtils.getBaseName(fileName) + "-" + randomStr + "." + fileExtension;

            String filePath = fileBasePath + newFileName;
            File dest = new File(filePath);
            //存储文件
            file.transferTo(dest);
            // 存储文件地址
            practiceCourseDao.update(null, new LambdaUpdateWrapper<PracticeCourse>()
                    .eq(PracticeCourse::getCourseId, courseId)
                    .set(PracticeCourse::getPath, filePath)
                    .set(PracticeCourse::getFilename, fileName)
                    .set(PracticeCourse::getCreateTime, new Date()));
            return new R(Code.SAVE_OK, filePath, "文件上传成功");


        } catch (IOException e) {
            e.printStackTrace();

            return new R(Code.SAVE_ERR, null, "文件上传失败，请稍后重试");


        }
    }
}
